'use strict';
const db = uniCloud.database();

/**
 * 云函数：获取所有用户的排行榜
 * @param {Object} event - 请求参数
 * @returns {Object} - 排行榜数据
 */
exports.main = async (event, context) => {
  try {
    const userCollection = db.collection('users');
    const checkinCollection = db.collection('checkins');

    // 查询签到排行榜
    const checkinRankings = await checkinCollection
      .aggregate()
      .group({
        _id: '$user_id',
        checkin_count: { $sum: 1 }
      })
      .lookup({
        from: 'users',
        localField: '_id',
        foreignField: '_id',
        as: 'user'
      })
      .unwind('$user')
      .project({
        _id: '$user._id',
        name: '$user.name',
        checkin_count: 1
      })
      .sort({ checkin_count: -1 }) // 根据签到次数排序
      .limit(10) // 取前10名
      .end();

    // 查询连续签到排行榜
    const consecutiveRankings = await userCollection
      .where({ role: 'student' })
      .field({ _id: 1, name: 1, consecutive_days: 1 })
      .orderBy('consecutive_days', 'desc') // 根据连续签到天数排序
      .limit(10)
      .get();

    // 查询积分排行榜
    const pointsRankings = await userCollection
      .where({ role: 'student' })
      .field({ _id: 1, name: 1, points: 1 })
      .orderBy('points', 'desc') // 根据积分排序
      .limit(10)
      .get();

    return {
      code: 0,
      data: [
        {
          title: '签到次数排行榜',
          items: checkinRankings.data.map(item => ({
            name: item.name,
            value: item.checkin_count
          }))
        },
        {
          title: '连续签到排行榜',
          items: consecutiveRankings.data.map(item => ({
            name: item.name,
            value: item.consecutive_days
          }))
        },
        {
          title: '积分排行榜',
          items: pointsRankings.data.map(item => ({
            name: item.name,
            value: item.points
          }))
        }
      ],
      msg: '获取排行榜成功'
    };
  } catch (e) {
    console.error('获取排行榜失败:', e);
    return { code: -1, msg: '获取排行榜失败' };
  }
};